package com.zmn.oms.common.discount.impl;

import com.zmn.oms.common.discount.dto.CalculateDiscountListDTO;
import com.zmn.oms.common.discount.dto.CalculateDiscountResultDTO;
import com.zmn.oms.common.discount.interfaces.DiscountCalculateRuleService;
import com.zmn.oms.common.discount.interfaces.DiscountCalculator;
import com.zmn.oms.common.dto.ResultDTO;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * 类描述： 抽象类
 *
 * @author heciqi
 * @date 2018/12/07 21:17
 */
public abstract class AbsDiscountCalculatorImpl implements DiscountCalculateRuleService {

	/**
	 * 是否能优惠
	 *
	 * @param origDiscounts 优惠列表
	 * @return
	 */
	@Override
	public ResultDTO canDiscount(List<CalculateDiscountListDTO> origDiscounts) {
		return new ResultDTO(true, "");
	}

	/**
	 * 计算优惠金额
	 *
	 * @param origDiscounts 原有优惠列表
	 * @param initialAmount 初始金额（在该金额基础上计算优惠）
	 * @param calculator    回调实现各自计算
	 * @return 返回计算模型
	 */
	@Override
	public CalculateDiscountResultDTO calculate(List<CalculateDiscountListDTO> origDiscounts, Integer initialAmount, DiscountCalculator calculator) {
		// 计算原有优惠总额
		int origDiscountAmount = 0;
		if (!CollectionUtils.isEmpty(origDiscounts)) {
			origDiscountAmount = origDiscounts.stream().mapToInt(value -> value.getAmount()).sum();
		}

		// 优惠金额
		int discountAmount = calculator.calcDiscount(initialAmount);

		// 优惠后金额（实付金额）
		int discountAfterAmount;
		if (discountAmount > initialAmount) {
			discountAmount = initialAmount; // 优惠金额大于基础金额时 ，优惠金额等于基础金额
			discountAfterAmount = 0;
		} else {
			discountAfterAmount = initialAmount - discountAmount;
		}

		// 优惠总额
		int totalDiscountAmount = origDiscountAmount + discountAmount;

		CalculateDiscountResultDTO discountResultDTO = new CalculateDiscountResultDTO();
		discountResultDTO.setDiscountAmount(discountAmount);
		discountResultDTO.setOrigDiscountAmount(origDiscountAmount);
		discountResultDTO.setTotalDiscountAmount(totalDiscountAmount);
		discountResultDTO.setAfterDiscountAmount(discountAfterAmount);

		return discountResultDTO;
	}
}
